#include "aiai/aiai_filewrite.hpp"

aiai_filewrite::aiai_filewrite(std::string fileName)
{
    filename = fileName;
    isfirstwrite = true;
    fp = nullptr;
}

aiai_filewrite::~aiai_filewrite()
{
    if(fp != nullptr)
    {
        close();
    }
}

int aiai_filewrite::write(unsigned char *buff, int size)
{
    if(isfirstwrite == true)
    {
        fp = fopen(filename.c_str(), "wb");
        if( nullptr == fp ){
            printf("open file error!\n");
            return -1;
        }
        isfirstwrite = false;
    }

    int ret = fwrite(buff, sizeof(unsigned char), size, fp);
    fflush(fp);
    if(ret < 0){
            printf("read data error!\n");
            return -1;
    }
    return ret;
}

void aiai_filewrite::close()
{
    fclose(fp);
    fp = nullptr;
    isfirstwrite = true;
}
